import NotFound from '@/components/NotFound';
import { faArrowLeft, faBackward } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import { motion } from 'framer-motion';
import React, { useEffect, useState, version } from 'react';
import cls from 'classnames';
import {
  Route,
  Switch,
  useHistory,
  useRouteMatch,
  useLocation,
} from 'react-router';
import Configuration from './Configuration';

import styles from './index.module.scss';
import Explore from './Explore';
import { createTaskVersion, getAllVersion, listTaskVersion } from '@/api';

const tabMap = {
  config: '任务配置',
  explore: '探索结果',
  analyze: '效用分析',
  risk: '风险分析',
};

const _tabs = Object.entries(tabMap).map((entry) => ({
  key: entry[0],
  label: entry[1],
  checked: false,
  canRead: false,
}));

function Task() {
  const {
    params: { taskId },
  } = useRouteMatch<{ taskId: string }>();
  const { path } = useRouteMatch();
  const location = useLocation();
  const history = useHistory();
  const [tabs, setTabs] = useState(_tabs);
  const [versions, setVersions] = useState<TaskVersion[]>([]);
  const [currentVersion, setCurrentVersion] = useState('init');
  console.log(tabs);
  useEffect(() => {
    console.log(location.pathname);
    setTabs((prevTabs) => {
      for (let i = 0; i < prevTabs.length; i++) {
        prevTabs[i].checked = location.pathname.endsWith(prevTabs[i].key);
      }

      return [...prevTabs];
    });
    getAllVersion(taskId).then((e) => {
      console.log('all task version', e.data);
      setVersions(e.data);
    });
  }, [location]);
  useEffect(() => {
    console.log('tabs', tabs);
  }, [tabs]);

  const switchTab = (key: string) => {
    history.push(
      location.pathname.replace(
        /^(\/task\/[a-z0-9_-]+\/[a-z0-9_-]+\/)(.+)/g,
        '$1' + key
      )
    );
  };

  useEffect(() => {
    // 初始化项目
    // (async () => {
    //   const { data: versionList } = await listTaskVersion(taskId);
    //   console.log('version', versionList);
    //   setVersions(versionList);
    //   if (versionList.length === 0) {
    //     // 没有版本，创建一个
    //     const versionName = prompt('还没有版本，请输入版本名称');
    //     if (!versionName) {
    //       alert('请输入版本名称');
    //       window.location.reload();
    //       return;
    //     }
    //     await createTaskVersion(taskId, versionName);
    //   }
    //   const lastId = Math.max(...versionList.map((item) => item.id));
    //   console.log('last id', lastId);
    //   setCurrentVersion(
    //     versionList.find((version) => version.id === lastId)?.versionName ?? ''
    //   );
    // })();
  }, []);

  useEffect(() => {
    history.push(`/task/${taskId}/${currentVersion}/config`);
  }, [currentVersion]);

  return (
    <div>
      <motion.div
        style={{
          width: '12rem',
          height: '3rem',
          cursor: 'pointer',
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
        }}
        whileHover={{ scale: 1.1 }}
      >
        <h1 onClick={() => history.push('/dash')}>
          <FontAwesomeIcon
            icon={faArrowLeft}
            style={{ fontSize: '2rem', marginRight: 10 }}
          />
          回到首页
        </h1>
      </motion.div>
      <Select
        labelId="demo-simple-select-label"
        id="demo-simple-select"
        style={{ marginTop: '2rem' }}
        value={currentVersion}
        onChange={(e) => {
          setCurrentVersion(e.target.value);
        }}
      >
        {versions.map((version) => (
          <MenuItem value={version.versionUuid}>{version.createTime}</MenuItem>
        ))}
      </Select>
      <div>
        <ul className={styles['task-tab']}>
          {tabs.map(({ key, label, checked, canRead }) => (
            <motion.li
              aria-disabled
              key={key}
              className={cls(
                styles['task-tab-item'],
                canRead ? styles['active'] : styles['inactive']
              )}
              whileHover={{
                skewX: 2,
                backgroundColor: '#90a3bb',
                color: '#000000',
              }}
              onClick={() => switchTab(key)}
              animate={
                checked
                  ? {
                      skewX: 2,
                      backgroundColor: '#90a3bb',
                      color: '#000000',
                    }
                  : {
                      skewX: 0,
                      backgroundColor: '#424b56',
                      color: '#c1c6cb',
                    }
              }
            >
              {label}
            </motion.li>
          ))}
        </ul>
      </div>

      <Switch>
        <Route path={path} exact>
          你没选择任何任务
        </Route>
        <Route path={`${path}/:id/config`}>
          <Configuration />
        </Route>
        <Route path={`${path}/:id/explore`}>
          <Explore />
        </Route>
        <Route path={`${path}/:id/analyze`}>Result</Route>
        <Route path={`${path}/:id/risk`}>Result</Route>
        <Route path="*">
          <NotFound />
        </Route>
      </Switch>
    </div>
  );
}

export default Task;
